package com.lry.jvm.classfile;

import com.lry.jvm.classfile.attributes.AttributeInfo;
import com.lry.jvm.classfile.attributes.CodeAttribute;
import com.lry.jvm.classfile.attributes.ConstantValueAttribute;
import com.lry.jvm.classfile.constantpool.ConstantPool;
import lombok.Getter;

//方法和属性
@Getter
public class MemberInfo {

    private ConstantPool cp;

    private int accessFlags;
    private int nameIndex;
    private int descriptorIndex;
    private AttributeInfo[] attributes;

    public MemberInfo(ConstantPool constantPool, ClassReader reader) {
        cp = constantPool;
        accessFlags = reader.nextU2ToInt();
        nameIndex = reader.nextU2ToInt();
        descriptorIndex = reader.nextU2ToInt();
        attributes = AttributeInfo.readAttributes(reader, cp);
    }

    public String name(){
        return cp.getUTF8(nameIndex);
    }

    public String descriptor(){
        return cp.getUTF8(descriptorIndex);
    }

    public CodeAttribute codeAttribute(){
        for(AttributeInfo attrInfo:attributes){
            if(attrInfo instanceof CodeAttribute){
                return (CodeAttribute) attrInfo;
            }
        }
        return null;
    }

    public static MemberInfo[] readMembers(ConstantPool cp,ClassReader reader){
        int fieldCount = reader.nextU2ToInt();
        MemberInfo[] fields = new MemberInfo[fieldCount];
        for(int i=0;i<fieldCount;i++){
            fields[i] = new MemberInfo(cp,reader);
        }
        return fields;
    }

    public ConstantValueAttribute constantValueAttribute(){
        for(AttributeInfo attrInfo:attributes){
            if(attrInfo instanceof ConstantValueAttribute){
                return (ConstantValueAttribute) attrInfo;
            }
        }
        return null;
    }
}
